<template>
  <!-- 搜索表单-->

  <!-- <el-button type="primary" @click="handleSearch">查询</el-button> -->
  <el-button type="primary" @click="handleCreate">新增</el-button>
  <!-- <el-button type="danger" @click="handleBatchDelete">批量删除</el-button> -->

  <!-- 添加数据对话框 -->
  <el-dialog title="提示" v-model="dialogVisible" width="500px">
    <el-form ref="formAdd" :model="employee" label-width="80px">
      <el-form-item label="员工编号">
        <el-input v-model="employee.id"></el-input>
      </el-form-item>
      <el-form-item label="员工姓名">
        <el-input v-model="employee.employeeName"></el-input>
      </el-form-item>
      <el-form-item label="岗位">
        <el-input v-model="employee.department"></el-input>
      </el-form-item>
      <el-form-item label="职位">
        <el-input v-model="employee.position"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="addEmployee">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!-- 编辑数据对话框 -->
  <el-dialog title="提示" v-model="dialogVisibleEdit" width="30%">
    <el-form ref="form" :model="employee" label-width="80px">
      <el-form-item label="员工编号">
        <el-input v-model="employee.id" disabled></el-input>
      </el-form-item>
      <el-form-item label="员工姓名">
        <el-input v-model="employee.employeeName"></el-input>
      </el-form-item>
      <el-form-item label="岗位">
        <el-input v-model="employee.department"></el-input>
      </el-form-item>
      <el-form-item label="职位">
        <el-input v-model="employee.position"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleEdit">提交</el-button>
        <el-button @click="dialogVisibleEdit = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!-- 表格数据 -->
  <el-table :data="tableData" style="width: 100%" :row-class-name="tableRowClassName" :loading="loading" class="my-table">
    <el-table-column type="selection" width="55"></el-table-column>
    <el-table-column type="index" label="序号" :index="1" width="100"></el-table-column>
    <el-table-column prop="id" label="员工编号" align="center"></el-table-column>
    <el-table-column prop="employeeName" label="员工姓名" align="center"></el-table-column>
    <el-table-column prop="department" label="岗位" align="center"></el-table-column>
    <el-table-column prop="position" label="职位" align="center"></el-table-column>
    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-button type="primary" size="small" @click="handleUpdate(scope.row)">编辑</el-button>
        <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[5, 10, 15, 20]"
    v-model:current-page="currentPage" v-model:page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
    :total="parseInt(totalCount)">
  </el-pagination>
</template>

<script>
import axios from 'axios';
import { reactive, ref } from 'vue';
const API_URL = 'http://localhost:8080/employees'; // 替换为实际的 API 地址
const formAdd = ref();
export default {
  data() {
    return {
      pageSize: 10,
      currentPage: 1,
      totalCount: 0,
      tableData: [],
      dialogVisible: false,
      dialogVisibleEdit: false,
      totalCount: 0,
      employee: {
        id: '',
        employeeName: '',
        department: '',
        position: '',
      },
      loading: false,
    };
  },
  mounted() {
    this.getAll();
  },
  methods: {


    async handleSearch() {
      this.currentPage = 1;
      this.pageSize = 10;
      this.getAll();
    },

    getAll() {
      this.loading = true;
      //发送ajax请求
      axios
        .get(
          'http://localhost:8080/employees/page?currentPage=' +
          this.currentPage +
          '&pageSize=' +
          this.pageSize
        )
        .then((res) => {
          console.log(res.data);
          console.log(res.data.data.rows);
          //设置表格数据
          this.tableData = res.data.data.rows;
          this.totalCount = res.data.data.totalCount;
        })
    },
    //添加员工
    async addEmployee() {
      axios.post(API_URL, this.employee).then((res) => {
        console.log(res.data);
        //如果操作成功，关闭弹窗，显示数据
        if (res.data.code == 20011) {
          this.dialogVisible = false;
          this.$message.success("员工添加成功");
          this.resetForm(); // 重置表单
        } else if (res.data.code == 20010) {
          this.$message.error("员工添加失败");
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(() => {
        //3取消添加
        this.$message.error("取消添加操作")
      });
    },

    //弹出添加敞口
    handleCreate() {
      this.dialogVisible = true;
      this.resetForm();
    },
    //重置表单
    resetForm() {
      this.employee = { ...this.employeeForm };
    },

    //删除员工
    async handleDelete(row) {
      //1.弹窗提示框
      this.$confirm("此操作永久删除当前数据，是否继续？", "提示", {
        type: 'info'
      }).then(() => {
        //2.作删除业务
        axios.delete(`${API_URL}/${row.id}`).then((res) => {
          if (res.data.code == 20021) {
            this.$message.success("删除成功");
            this.getAll();
          } else {
            this.$message.error("删除失败")
          }
        });
      }).catch(() => {
        //3取消删除
        this.$message.error("取消删除操作")
      });
    },

    //
    async handleBatchDelete(row) {
      const selectedRows = this.tableData.filter(row => row.selected);
      console.log(selectedRows);
      if (selectedRows.length === 0) {
        this.$message.warning('请先选择要删除的员工记录');
        return;
      }

      this.$confirm('此操作将永久删除选中的员工记录，是否继续？', '提示', {
        type: 'info'
      })
        .then(() => {
          const deletePromises = selectedRows.map(row => axios.delete(`${API_URL}/${row.id}`));
          Promise.all(deletePromises)
            .then(() => {
              this.$message.success('批量删除成功');
              this.getAll();
            })
            .catch(() => {
              this.$message.error('批量删除失败');
            });
        })
        .catch(() => {
          this.$message.info('取消删除操作');
        });
    },


    async handleUpdate(row) {
      console.log('ddddddd', row);
      this.employee = { ...row };
      this.dialogVisibleEdit = true;
    },

    //修改员工信息
    async handleEdit() {
      try {
        await axios.put(API_URL, this.employee);
        this.dialogVisibleEdit = false;
        this.getAll();
        this.$message.success('员工更新成功');
      } catch (error) {
        console.error(error);
        this.$message.error('员工更新失败');
      }
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'table-row-even';
      }
      return '';
    },
    //分页
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.getAll();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      //点击后重新设置当前页码
      this.currentPage = val;
      this.getAll();
    },
  },
};
</script>

<style scoped>
.table-row-even {
  background-color: #f5f7fa;
}
</style>
